package cn.edu.ctbu.scoremg.interceptor;

import cn.edu.ctbu.scoremg.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        // 1. 检查登录状态
        if (user == null) {
            response.sendRedirect("/login");
            return false;
        }

        // 2. 检查角色权限
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin") && user.getRoleType() != 1) {
            response.sendError(403, "无权访问管理员功能");
            return false;
        }
        if (uri.startsWith("/teacher") && user.getRoleType() != 2) {
            response.sendError(403, "教师功能需教师身份");
            return false;
        }

        return true;
    }
}